<?php
namespace app\run\controller;

use think\Loader;

class Tool extends Run
{
    public function addm()
    {
        $this->setTitle("模型生成", 'operation');
        $this->assign->warning = '非程序员请谨慎操作！';
        $this->mdl->form = array(
            'model' => array(
                'type' => 'string',
                'name' => '模型名称',
                'elem' => 'text',
            )
        );
        if ($this->request->isPost()) {
            $data = $this->Form->data[$this->m];
            $model = Loader::parseName(trim($data['model']), 1);
            if (!$model) {
                $this->assign->mdl_error['model'] = '请填写模型名称';
            }
            if (!isset($this->assign->mdl_error)) {
                $dir = APP_PATH . 'common' . DS . 'model' . DS;
                if (!is_writeable($dir)) {
                    return $this->message('error', "模型common/model文件夹没有可写权限");
                }
                $path = $dir . $model . '.php';
                if (file_exists($path)) {
                    return $this->message('error', "模型common\model\\{$model}已经存在");
                }
                $addString = <<<MODEL
<?php
namespace app\common\model;

class $model extends App
{
    //关联模型
    public \$assoc = [];
    
    public function initialize()
    {        
        \$this->form = [
            'id' => [
            	'type' => 'integer',
            	'name' => 'ID',
            	'elem' => 'hidden',
            ],
            //其他字段
        ];
        call_user_func_array(['parent', __FUNCTION__], func_get_args());
    }
    
    /*
    //表单分组
    public \$formGroup = [
        'advanced' => '高级选项'
    ];
    */
    
    //数据验证    
    protected \$_validate = [];
}

MODEL;
                file_put_contents($path, $addString);
                return $this->message('success', '操作已成功');
            }
        }
        $this->fetch = 'form';
    }

    public function addc()
    {
        $this->setTitle("控制器生成", 'operation');
        $this->assign->warning = '非程序员请谨慎操作！';
        $this->mdl->form = array(
            'controller' => array(
                'type' => 'string',
                'name' => '控制器名称',
                'elem' => 'text',
            ),
            'module' => array(
                'type' => 'string',
                'name' => '生成模块',
                'elem' => 'checkbox',
                'options' => ['run' => '后台', 'home' => '前台']
            ),
        );

        if ($this->request->isPost()) {
            $data = $this->Form->data[$this->m];
            $controller = Loader::parseName(trim($data['controller']), 1);
            $modules = $data['module'];
            if (!$controller) {
                $this->assign->mdl_error['controller'] = '请填写控制器的名称';
            }
            if (empty($modules)) {
                $this->assign->mdl_error['module'] = '请选择控制器生成模块';
            }

            if (!isset($this->assign->mdl_error)) {
                foreach ($modules as $module) {
                    $dir = APP_PATH . $module . DS . 'controller' . DS;
                    if (!is_writeable($dir)) {
                        return $this->message('error', "模块{$module}/controller文件夹没有可写权限");
                    }
                    $path = $dir . $controller . '.php';
                    if (file_exists($path)) {
                        return $this->message('error', "控制器{$module}\controller\\{$controller}已经存在");
                    }

                    $extends = ucfirst($module);
                    if ($module == 'run') {
                        $addString = <<<CONTROLLER
<?php
namespace app\\$module\controller;

class $controller extends $extends
{
    //初始化 需要调父级方法
    public function _initialize()
    {        
        call_user_func(['parent', __FUNCTION__]); 
    }
    
    //列表 
    public function lists()
    {
        if (!\$this->local['list_fields']) {
            \$this->local['list_fields'] = [
                'title'
            ];
        }
        return call_user_func(['parent', __FUNCTION__]);
    }
    
    //添加
    public function create()
    {        
        return call_user_func(['parent', __FUNCTION__]);
    }
    
    //修改
    public function modify()
    {        
        return call_user_func(['parent', __FUNCTION__]);
    } 
    
    //删除
    public function delete()
    {        
        return call_user_func(['parent', __FUNCTION__]);
    }  
}

CONTROLLER;
                    } else {
                        $addString = <<<CONTROLLER
<?php
namespace app\\$module\controller;

class $controller extends $extends
{
    //初始化 需要调父级方法
    public function _initialize()
    {        
        call_user_func(['parent', __FUNCTION__]); 
    }
}

CONTROLLER;
                    }
                    file_put_contents($path, $addString);
                }
                return $this->message('success', '操作已成功');
            }
        }
        $this->fetch = 'form';
    }
    
    function getSiteSize()
    {
        if ($this->request->isAjax()) {
            set_time_limit(0);
            echo $this->ajax('success',return_size(getDirSize(dirname(APP_PATH))));
        } 
        
        exit ;
    }
    
    function getLog()
    {        
        include  LIBS_VENDOR_PATH . 'Pclzip' . DS . 'pclzip.lib.php';
        $filepath = WWW_ROOT . 'tempfile' . DS . 'log_' . date('Ymd') . '.zip';
        $logszip = new \PclZip($filepath);
        $zipList = $logszip->create(LOG_PATH, PCLZIP_OPT_REMOVE_ALL_PATH);  
        if ($zipList == 0) {
            $this->message('error', '日志文件压缩失败:' . $logszip->errorInfo(true));
        }
        ob_end_clean();
        header("Content-Type: application/force-download;"); 
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize($filepath));
        header("Content-Disposition: attachment; filename=" . 'log_' . date('Ymd') . '.zip'); 
        header("Expires: 0");
        header("Cache-control: private");
        header("Pragma: no-cache"); 
        readfile($filepath);         
        exit ;
    }
    
    function removeLog()
    {
        if ($this->request->isAjax()) {
            removeDir(LOG_PATH);
            return $this->ajax('success','日志清除成功！');
        }
    }
    
    function removeTemp()
    {
        if ($this->request->isAjax()) {
            removeDir(RUNTIME_PATH . 'temp');
            removeDir(WWW_ROOT . 'tempfile');
            return $this->ajax('success','临时文件清除成功！');
        }
    }
    
    public function clearCache()
    {
        if ($this->request->isAjax()) {
            \think\Cache::clear(); 
            return $this->ajax('success','缓存清除成功！');
        }
    }
    
    public function switchTrace()
    {
        if ($this->request->isAjax()) {
            $is_trace = intval(!config('app_trace'));
            $this->loadModel('Setting');
            $this->Setting->where(['vari' => 'is_trace'])->update(['value' => $is_trace]);
            $this->Setting->write_cache();
            if($is_trace)
                return $this->ajax('success','Trace已启用');
            else
                return $this->ajax('success','Trace已关闭');
        }
    }
}
  